package org.summer.lawyer.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.summer.common.core.domain.R;
import org.summer.common.core.enums.UserStatus;
import org.summer.common.core.exception.ServiceException;
import org.summer.common.core.validate.AddGroup;
import org.summer.common.core.validate.EditGroup;
import org.summer.common.excel.utils.ExcelUtil;
import org.summer.common.idempotent.annotation.RepeatSubmit;
import org.summer.common.log.annotation.Log;
import org.summer.common.log.enums.BusinessType;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.common.web.core.BaseController;
import org.summer.lawyer.constant.SystemConstants;
import org.summer.lawyer.domain.bo.lawfirm.LawFirmBo;
import org.summer.lawyer.domain.vo.lawfirm.LawFirmCreateVo;
import org.summer.lawyer.domain.vo.lawfirm.LawFirmUpdateVo;
import org.summer.lawyer.domain.vo.lawfirm.LawFirmVo;
import org.summer.lawyer.domain.vo.wxuser.WxUserVo;
import org.summer.lawyer.service.ILawFirmService;
import org.summer.lawyer.service.IWxUserService;
import org.summer.lawyer.util.IdWorkerUtil;
import org.summer.system.domain.bo.SysDictDataBo;
import org.summer.system.domain.vo.SysDictDataVo;
import org.summer.system.service.ISysDictDataService;

import java.util.List;

/**
 * 律所信息
 *
 * @author summer
 * @date 2024-06-15
 */
@Tag(name = "后台相关接口", description = "后台律所律师信息相关接口")
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/lawyer/lawFirm")
public class LawFirmController extends BaseController {

    private final ILawFirmService lawFirmService;

    private final IWxUserService wxUserService;
    private final ISysDictDataService sysDictDataService;

    /**
     * 查询律所信息列表
     */
    @Operation(summary = "查询律所信息列表", description = "查询律所信息列表", responses = {@ApiResponse(responseCode = "200", description = "成功")})
    @SaCheckPermission("lawfirm:info:list")
    @GetMapping("/list")
    public TableDataInfo<LawFirmVo> list(LawFirmVo vo, PageQuery pageQuery) {
        return lawFirmService.selectPageList(vo, pageQuery);
    }

    /**
     * 导出律所信息列表
     */
    @SaCheckPermission("lawfirm:info:export")
    @Log(title = "律所信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(LawFirmVo vo, HttpServletResponse response) {
        List<LawFirmVo> list = lawFirmService.selectLawFirmVoList(vo);
        ExcelUtil.exportExcel(list, "律所信息", LawFirmVo.class, response);
    }

    /**
     * 获取律所信息详细信息
     *
     * @param lawFirmId 主键
     */
    @SaCheckPermission("lawfirm:info:query")
    @GetMapping("/{lawFirmId}")
    public R<LawFirmVo> getInfo(@NotNull(message = "主键不能为空")
                                @PathVariable Long lawFirmId) {
        return R.ok(lawFirmService.selectLawFirmVoById(lawFirmId));
    }

    /**
     * 新增律所信息
     */
    @SaCheckPermission("lawfirm:info:add")
    @Log(title = "律所信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/saveLawFirm")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody LawFirmCreateVo vo) {
        WxUserVo wxUserVo = new WxUserVo();
        wxUserVo.setAccount(vo.getAccount());
        if (wxUserService.checkAccountUnique(wxUserVo)) {
            return R.fail("新增'" + vo.getLawFirmName() + "'失败，登录账号已存在");
        }
        ;
        LawFirmVo lawFirmVo = new LawFirmVo();
        lawFirmVo.setContactPhone(vo.getContactPhone());
        lawFirmVo.setLawFirmName(vo.getLawFirmName());
        if (lawFirmService.checkPhoneUnique(lawFirmVo)) {
            return R.fail("新增'" + vo.getLawFirmName() + "'失败，手机号码已存在");
        }
        return toAjax(lawFirmService.insertByVo(vo));
    }

    /**
     * 修改律所信息
     */
    @SaCheckPermission("lawfirm:info:edit")
    @Log(title = "律所信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/updateLawFirm")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody LawFirmUpdateVo vo) {
//        WxUserVo wxUserVo  = new WxUserVo();
//        wxUserVo.setAccount(vo.getAccount());
//        wxUserVo.setWxUserId(vo.getAdminUserId());
//        if(wxUserService.checkAccountUnique(wxUserVo)){
//            return R.fail("修改信息'" + vo.getLawFirmName() + "'失败，登录账号已存在");
//        };
//        LawFirmVo lawFirmVo = new LawFirmVo();
//        lawFirmVo.setContactPhone(vo.getContactPhone());
//        lawFirmVo.setLawFirmId(vo.getLawFirmId());
//        if(lawFirmService.checkPhoneUnique(lawFirmVo)){
//            return R.fail("修改信息'" + vo.getLawFirmName() + "'失败，手机号码已存在");
//        }
        return toAjax(lawFirmService.updateByVo(vo));
    }

    /**
     * 删除律所信息
     *
     * @param lawFirmIds 主键串
     */
    @SaCheckPermission("lawfirm:info:remove")
    @Log(title = "律所信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeLawFirm/{lawFirmIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] lawFirmIds) {
        return toAjax(lawFirmService.deleteWithValidByIds(List.of(lawFirmIds), true));
    }

    @SaCheckPermission("lawfirm:info:inactive")
    @Log(title = "冻结律所账户", businessType = BusinessType.UPDATE)
    @PostMapping("/inactiveLawFirm")
    public R<Void> inactiveLawFirm(@RequestBody LawFirmBo bo) {
        bo.setStatus(UserStatus.DISABLE.getCode());
        lawFirmService.changeLawFirmStatus(bo);
        return R.ok();
    }

    @SaCheckPermission("lawfirm:info:active")
    @Log(title = "启用律所账户", businessType = BusinessType.UPDATE)
    @PostMapping("/activeLawFirm")
    public R<Void> activeLawFirm(@RequestBody LawFirmBo bo) {
        bo.setStatus(UserStatus.OK.getCode());
        lawFirmService.changeLawFirmStatus(bo);
        return R.ok();
    }

    /**
     * 擅长列表
     */
    @SaCheckPermission("lawfirm:expertise:list")
    @GetMapping("/listExpertise")
    public TableDataInfo<SysDictDataVo> listExpertise(SysDictDataBo bo, PageQuery pageQuery) {
        bo.setDictType(SystemConstants.LAWYER_EXPERTISE);
        return sysDictDataService.selectPageDictDataList(bo, pageQuery);
    }

    /**
     * 新增擅长数据
     */
    @Log(title = "新增律师擅长", businessType = BusinessType.INSERT)
    @SaCheckPermission("lawfirm:expertise:add")
    @PostMapping("/createExpertise")
    public R<Void> createExpertise(@RequestBody SysDictDataBo bo) {
        bo.setDictType(SystemConstants.LAWYER_EXPERTISE);
        bo.setDictLabel(IdWorkerUtil.nextIdStr());
       if(!sysDictDataService.checkDictDataUnique(bo)){
           throw new ServiceException(StrUtil.format("“{}”已经存在，请勿重复添加",bo.getDictValue()));
       }
        SysDictDataBo queryBo = new SysDictDataBo();
        queryBo.setDictType(SystemConstants.LAWYER_EXPERTISE);
        List<SysDictDataVo> dictDataVoList = sysDictDataService.selectDictDataList(queryBo);
        int sort = 1;
        if (CollUtil.isNotEmpty(dictDataVoList)) {
            sort = dictDataVoList.size() + 1;
        }
        bo.setDictSort(sort);
        sysDictDataService.insertDictData(bo);
        return R.ok();
    }

    /**
     * 删除律师擅长信息
     */
    @Log(title = "删除律师擅长信息", businessType = BusinessType.DELETE)
    @SaCheckPermission("lawfirm:expertise:remove")
    @DeleteMapping("/removeExpertise/{ids}")
    public R<Void> removeExpertise(@NotEmpty(message = "主键不能为空") @PathVariable("ids") Long[] ids) {
        sysDictDataService.deleteDictDataByIds(ids);
        return R.ok();
    }

    /**
     * 修改律师擅长信息
     */
    @Log(title = "修改律师擅长信息", businessType = BusinessType.UPDATE)
    @SaCheckPermission("lawfirm:expertise:edit")
    @PostMapping("/updateExpertise")
    public R<Void> updateExpertise(@RequestBody SysDictDataBo bo) {
       // bo.setDictType(SystemConstants.LAWYER_EXPERTISE);
        if(!sysDictDataService.checkDictDataUnique(bo)){
            throw new ServiceException(StrUtil.format("“{}”已经存在，请勿重复添加", bo.getDictValue()));
        }
        sysDictDataService.updateDictData(bo);
        return R.ok();
    }

    /**
     * 查询律师擅长详情
     */
    @SaCheckPermission("lawfirm:expertise:query")
    @GetMapping("/expertise/{id}")
    public R<SysDictDataVo> getExpertise(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(sysDictDataService.selectDictDataById(id));
    }

}
